<template>
  <div class="container">
    <!-- 添加数据按钮 -->
    <div class="action-btn">
      <el-button type="primary" @click="handleAddData" plain round>添加数据</el-button>
    </div>

    <!-- 美化后的筛选表单 -->
    <el-form
        class="filter-form-container"
        :model="filterForm"
        label-position="top"
    >
      <!-- 时间选择器组 -->
      <div class="date-picker-group">
        <el-form-item label="查询时间段" class="date-label">
          <el-date-picker
              v-model="filterForm.start_date"
              type="datetime"
              placeholder="选择开始日期"
              class="date-picker"
          />
          <el-date-picker
              v-model="filterForm.end_date"
              type="datetime"
              placeholder="选择结束日期"
              class="date-picker"
          />
        </el-form-item>
      </div>

      <!-- 按钮组 -->
      <div class="button-group">
        <el-button
            type="primary"
            @click="handleDownloadWordOne"
            class="primary-btn"
            round
        >
          <i class="el-icon-download"></i> 批量导出到一张Word
        </el-button>
        <el-button
            type="success"
            @click="handleFilter"
            class="success-btn"
            round
        >
          <i class="el-icon-refresh"></i> 刷新数据
        </el-button>
      </div>
    </el-form>
    <!--    添加一个按钮-->


    <!-- 数据表格 -->
    <el-table
        class="data-table"
        :data="tableData.value"
        border
        style="width: 100%; margin-top: 20px;"
        v-loading="table_loading"
        @selection-change="handleSelectionChange">
      <el-table-column
          prop="choose_id"
          label="选择"
          align="center"
          type="selection" width="55"
      >
      </el-table-column>
      <el-table-column
          v-for="(value, key) in get_reportInfo"
          :key="key"
          :prop="key"
          :label="value.verbose_name"
          :width="value.width || 120"
          align="center"
      ></el-table-column>

      <el-table-column prop="attachment" label="附件" width="150" align="center">
        <template #default="scope">
          <div class="attachment-cell">
            <a
                :href="scope.row.attachment"
                target="_blank"
                class="attachment-link"
            >{{ scope.row.attachmentText || '附件' }}</a>
            <el-button
                type="primary"
                size="small"
                @click="handleFileUpload(scope.row)"
                class="upload-btn"
            >上传
            </el-button>
          </div>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="200" align="center">
        <template #default="scope">
          <div class="action-buttons">
            <el-button
                type="text"
                @click="handleClickDelete(scope.row)"
                class="action-btn"
            >删除
            </el-button>
            <el-button
                type="text"
                @click="handleClickEdit(scope.row)"
                class="action-btn"
            >编辑
            </el-button>
            <el-button
                type="success"
                text
                @click="handleClickDownlaodWord(scope.row)"
                class="action-btn"
            >导出Word
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
          v-model:currentPage="filterForm.page"
          :page-size="10"
          layout="prev, pager, next"
          :total="total_datas"
          @current-change="handleCurrentChange"
          background
      />
    </div>

    <!-- 弹窗组件 -->
    <AddData :isAdmin="false"
             @refresh-table="handleSucceedAdd"
             ref="addDataComponent"
    />
    <EditData :isAdmin="false"
              @refresh-table="handleSucceedEdit"
              ref="editDataComponent"
    />

    <!-- 文件上传 -->
    <input
        type="file"
        style="display: none;"
        ref="fileInput"
        @change="onFileSelected"
    />
  </div>
</template>

<script setup>
import {ref, onMounted, watchEffect, onBeforeUnmount, reactive} from 'vue';
import setting from '@/setting.js';
import {ElMessage, ElMessageBox} from "element-plus";

import global, {formDataApi, jsonApi} from "@/global.js";
import AddData from "@/components/Main/TeachingAffairsManagement/CourseAdjustmentManagement/public_tools/AddData.vue";
import EditData from "@/components/Main/TeachingAffairsManagement/CourseAdjustmentManagement/public_tools/EditData.vue";

const props = defineProps({
  tableType: {
    type: String,
    required: true
  }
});
const filterForm = reactive({
  start_date: '',
  end_date: '',
  page: 1,
});
// State
const reportInfo = ref({});
const get_reportInfo = ref({});
const tableData = reactive([]);
let orgTableData = null;//原始数据，其中的json没有经过json.parse
const fileInput = ref(null);
let currentRow = ref(null);
let selectedRows = ref([]);
// 初始化 editInfo 为响应式对象
const editInfo = reactive({
  editData: null,
  ID: null,
});
const table_loading = ref(false);
let total_datas = ref(0);


//子组件对象声明
const addDataComponent = ref(null);
const editDataComponent = ref(null);

onMounted(() => {
  //开启接收事件监听
  // 获取当前日期
// 设置结束日期为今天
  const now = new Date();
  // 拼接成 "yyyy-MM-dd HH:mm:ss" 格式
  filterForm.end_date = new Date(Date.now() + 86400000).toISOString();
  // 判断当前日期属于哪个学期，并设置起始日期
  let start_date;
  if (now.getMonth() >= 7) { // 当前时间是8月到12月之间，开学时间应为8月1日
    start_date = new Date(now.getFullYear(), 7, 1); // 设置时间为8月1日
  } else if (now.getMonth() < 2) { // 当前时间是1月到1月，开学时间应为去年8月1日
    start_date = new Date(now.getFullYear() - 1, 7, 1); // 设置时间为去年8月1日
  } else { // 当前时间是2月到7月之间，开学时间应为2月1日
    start_date = new Date(now.getFullYear(), 1, 1); // 设置时间为2月1日
  }

  // 手动格式化日期为 "YYYY-MM-DD" 格式
  function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }

  // 设置filterForm.start_date为计算出的学期开始日期
  filterForm.start_date = formatDate(start_date);
});

// Methods
const handleAddData = () => {
  addDataComponent.value.dialogVisibleAdd = true;
};
const handleSucceedAdd = () => {
  ElMessage({
    message: '添加成功',
    type: 'success',
  });
  // 拼接成 "yyyy-MM-dd HH:mm:ss" 格式
  refreshTable();
};
const handleSucceedEdit = () => {
  ElMessage({
    message: '编辑成功',
    type: 'success',
  });
  refreshTable();
};
const handleFilter = () => {
  // 获取筛选条件
  getDataWithAccessToken(props.tableType);


};
const handleCurrentChange = (currentPage) => {
  // 更新当前页码
  filterForm.page = currentPage;
  // 重新加载数据
  getDataWithAccessToken(props.tableType);
};
const getDataWithAccessToken = async () => {
  const requestBody = {
    start_time: filterForm.start_date,
    end_time: filterForm.end_date,
    page: filterForm.page,
  };

  try {
    table_loading.value = true;
    const response = await jsonApi('/courseadjustmentmanagement/get/', JSON.stringify(requestBody));
    let orgdata = await response.json();
    const data = orgdata['datas'];
    total_datas = orgdata['total_datas'];
    orgTableData = JSON.parse(JSON.stringify(data));
    if (!response.ok) {
      showError('获取数据失败', data.error, 2000);
    } else {
      tableData.value = data; // 假设返回的数据直接用于表格

    }
    table_loading.value = false;
  } catch (error) {
    ElMessage({
      message: '获取数据失败',
      type: 'error',
      duration: 2000,
    });
    table_loading.value = false;
  }
};
const getCourseadJustmentInfo = async () => {
  //获取字段
  const response = await jsonApi('/courseadjustmentmanagement/getmodelfields/', "");
  const data = await response.json();
  if (response.ok) {
    localStorage.setItem('CourseadJustmentInfo', JSON.stringify(data));
    //await getCourseadJustmentInfo();
    //将字符串转为对象
    reportInfo.value = JSON.parse(localStorage.getItem('CourseadJustmentInfo'));
    get_reportInfo.value = reportInfo.value['TeacherChangeClassRecord']
    const get_excludeFields = ['model_name', 'attachment'];
    // 使用 forEach 循环来遍历对象的所有键
    get_excludeFields.forEach(field => {
      // 如果报告信息中存在要排除的字段，则删除它
      if (get_reportInfo.value.hasOwnProperty(field)) {
        delete get_reportInfo.value[field];
      }
    });
  } else {
    ElMessage(
        {
          message: '获取数据失败',
          type: 'error',
          duration: 2000,
        }
    );
  }

}

//删除表格数据
const handleClickDelete = async (row) => {

  try {
    const requestBody = {"id": row.id, "Report": props.tableType};
    const response = await jsonApi('/courseadjustmentmanagement/delete/', JSON.stringify(requestBody));
    const data = await response.json();

    if (data.code === 'token_not_valid') {
      if (await global.refreshAndRetry()) {
        //成功刷新重新执行
        await self.handleClickDelete();
      }
    } else if (!response.ok) {
      ElMessage({
        type: 'error',
        message: data.error || '删除失败'
      });
    } else {
      await refreshTable();
      ElMessage({
        type: 'success',
        message: '删除成功!'
      });
    }
  } catch (error) {
    console.error('删除过程中发生错误:', error);
    ElMessage({
      type: 'error',
      message: '网络错误，请重试'
    });
  }
}
//修改表格数据相关
const handleClickEdit =  (row) => {
  let data;
  // 返回orgTableData中的id==row.id的数据
  data = tableData.value.find(item => item.id === row.id);
  editInfo.editData = data;
  editInfo.ID = row.id;
  //开启修改组件
  editDataComponent.value.openComponent(editInfo);



}
//下载word
const handleSelectionChange = (selection) => {
  if (selection.length > 0) {
    selectedRows.value = selection;
  } else {
    selectedRows.value = [];
  }
}
const handleClickDownlaodWord = async (row) => {
  ElMessage({
    message: 'word导出后需调整格式后打印',
    type: 'info',
    duration: 2000
  })
  try {
    const response = await jsonApi('/courseadjustmentmanagement/downloadword/', JSON.stringify({"ids": [row.id]}));

    if (response.ok) {
      // 创建一个blob对象，它表示了一段不可变的原始数据
      const blob = await response.blob();

      // 创建一个链接元素，用于下载文件
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;

      // 设置下载的文件名，确保服务器在响应头中设置了正确的文件名
      let fileName = 'downloaded.docx'; // 默认文件名
      const contentDisposition = response.headers.get('content-disposition');
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename="?([^"]*)"?$/);
        if (fileNameMatch) {
          fileName = fileNameMatch[1]; // 使用从响应头中提取的文件名
        }
      }

      a.download = fileName;

      // 触发下载
      document.body.appendChild(a);
      a.click();

      // 清理资源
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } else {
      const data = await response.json();
      ElMessage({
        message: '下载失败: ' + data.error,
        type: 'error',

      })
    }
  } catch (e) {
    ElMessage({
      message: '下载失败: ' + e,
      type: 'error'

    })
  }
};
const handleDownloadWordOne = async (row) => {
  ElMessage({
    message: 'word导出后需调整格式后打印',
    type: 'info',
    duration: 2000
  })
  // rows 里面的每一个id组成
  const rows_ids = selectedRows.value.map(row => row.id);
  // 判定，term、type、change_type、reason_type、course_name信息有任意不一致才则直接报错
  if (selectedRows.value.some(row => row.term !== selectedRows.value[0].term || row.type !== selectedRows.value[0].type || row.change_type !== selectedRows.value[0].change_type || row.reason_type !== selectedRows.value[0].reason_type || row.course_name !== selectedRows.value[0].course_name)) {
    ElMessage({
      message: '下载失败: 请选择同一学期、同一时限类型、同一调整类型、同一原因类型、同一课程的数据',
      type: 'error',
    })
    return;
  }


  try {
    const response = await jsonApi('/courseadjustmentmanagement/downloadword/', JSON.stringify({"ids": rows_ids}));

    if (response.ok) {
      // 创建一个blob对象，它表示了一段不可变的原始数据
      const blob = await response.blob();

      // 创建一个链接元素，用于下载文件
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;

      // 设置下载的文件名，确保服务器在响应头中设置了正确的文件名
      let fileName = 'downloaded.docx'; // 默认文件名
      const contentDisposition = response.headers.get('content-disposition');
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename="?([^"]*)"?$/);
        if (fileNameMatch) {
          fileName = fileNameMatch[1]; // 使用从响应头中提取的文件名
        }
      }

      a.download = fileName;

      // 触发下载
      document.body.appendChild(a);
      a.click();

      // 清理资源
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } else {
      const data = await response.json();
      ElMessage({
        message: '下载失败: ' + data.error,
        type: 'error',

      })
    }
  } catch (e) {
    ElMessage({
      message: '下载失败: ' + e,
      type: 'error'

    })
  }
};

// 上传相关
const handleFileUpload = async (row) => {
  // 触发隐藏的 file input 的点击事件，以打开文件选择对话框
  fileInput.value.click();
  // 你可能需要在这里以某种方式将当前行数据传递给文件上传处理函数
  // 例如，可以将 row 保存在一个组件的数据属性中，以便稍后在文件选择后使用
  currentRow = row;
};
const onFileSelected = async (event) => {
  const file = event.target.files[0];
  if (file) {
    //检查file是不是pdf或者zip
    if (file.type === 'application/pdf' || file.type === 'application/x-zip-compressed') {
      // 显示上传进度
      // 在这里处理文件上传逻辑
      await uploadFile(currentRow, file);
    } else {
      // 显示错误消息
      ElMessage.error('请选择PDF或ZIP文件');
    }


  }
};
const uploadFile = async (row, file) => {
  // 创建 FormData 对象，并添加文件和其他可能需要的数据
  const formData = new FormData();
  const accessToken = localStorage.getItem('access_token');
  formData.append('file', file);
  formData.append('id', row.id); // 假设每一行数据有一个唯一的 id
  formData.append('Report', props.tableType); // 假设每一行数据有一个唯一的 id
  // 使用 Axios、Fetch API 或 XMLHttpRequest 发送文件到服务器
  try {
    // const response = await fetch(setting.API_URL + '/reportmanager/upload/', {
    //   method: 'POST',
    //   body: formData,
    //   headers: {
    //     'Authorization': `Bearer ${accessToken}`,
    //   },
    // });
    const response = await formDataApi('/courseadjustmentmanagement/upload/', formData)
    const data = await response.json();
    console.log(data);
    if (!response.ok) {
      ElMessage({
        type: 'error',
        message: data.error
      });


      throw new Error(`HTTP error! data: ${data}`);

    } else {
      ElMessage({
        type: 'success',
        message: '上传成功!'
      });
      await refreshTable();
      console.log('File uploaded successfully', data);

    }


  } catch (error) {
    console.error('文件上传失败', error);
  }
};


//刷新表格获取新数据
const refreshTable = async () => {
  // 获取新的数据
  filterForm.end_date = new Date(Date.now() + 86400000).toISOString();
  await getDataWithAccessToken();
};


watchEffect(async () => {
  await getCourseadJustmentInfo();
  await getDataWithAccessToken();
});


function showError(message, error, duration) {
  console.error(message, error);
  // 实现错误展示逻辑，例如使用通知组件
}
</script>


<style scoped>
.container {
  padding: 20px;
  background: #f5f7fa;
}

.action-btn {
  margin-bottom: 20px;
}

.filter-form {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.form-group {
  flex: 1 1 calc(50% - 7.5px);
}

@media (max-width: 768px) {
  .form-group {
    flex: 100%;
  }
}

.btn-group {
  display: flex;
  align-items: center;
}

.data-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.attachment-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.attachment-link {
  color: #409EFF;
  text-decoration: underline;
  cursor: pointer;
}

.upload-btn {
  padding: 6px 12px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.action-btn {
  margin: 4px 0;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.filter-form-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}

.date-picker-group {
  flex: 1 1 100%;
  display: flex;
  flex-direction: column;
}

.date-label {
  margin-bottom: 8px;
  font-weight: 500;
}

.date-picker {
  width: 220px;
  margin: 0 10px 10px 0;
}

.button-group {
  display: flex;
  gap: 15px;
  flex: 1 1 100%;
  justify-content: flex-end;
}

.primary-btn {
  background: linear-gradient(135deg, #6a11cb, #2575fc);
  border: none;
  color: white;
  padding: 12px 24px;
  font-size: 14px;
  transition: all 0.3s;
}

.primary-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.success-btn {
  background: linear-gradient(135deg, #1890ff, #64e572);
  border: none;
  color: white;
  padding: 12px 24px;
  font-size: 14px;
  transition: all 0.3s;
}

.success-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .button-group {
    flex-direction: column;
    align-items: flex-end;
  }
}
</style>